<script setup lang="ts">
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, ref } from "vue";
import { router } from "../router";
import { useLogging } from "../stores/logging";
import type { FavoriteRecord } from "../types/FavoriteRecord";
import type { ResultContext } from "../types/ResultContext";

const logging = useLogging();
const favoriteList = ref<FavoriteRecord[]>([]);

//从后端获取收藏数据
async function getcollections() {
  if (!logging.getUser?.id) {
    ElMessage.error("请先登录");
    return;
  }
  try {
    const res = await axios.get<ResultContext<FavoriteRecord[]>>(
      `http://localhost:8080/api/users/${logging.getUser.id}/favorites`,
    );
    favoriteList.value = res.data.data;
    logging.updateFavoriteCount(favoriteList.value.length);
  } catch (_error) {
    ElMessage.error("获取收藏列表失败");
  }
}
onMounted(() => {
  void getcollections();
});
// 取消收藏
async function cancelCollection(favoriteId: number) {
  if (!logging.getUser) {
    ElMessage.error("请先登录");
    return;
  }

  try {
    // 弹出确认框
    await ElMessageBox.confirm("确定要取消收藏这本书吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 确认后执行取消操作
    const res = await axios.delete<ResultContext<void>>(
      `http://localhost:8080/api/favorites/${favoriteId}`,
    );

    if (res.status === 204) {
      ElMessage.success("取消收藏成功！");
      favoriteList.value = favoriteList.value.filter(
        item => item.id !== favoriteId,
      );
      logging.updateFavoriteCount(favoriteList.value.length);
    } else {
      ElMessage.error(res.data.message || "取消收藏失败！");
    }
  } catch (error) {
    // 如果是取消操作引起的异常，可以忽略不提示
    if (error !== "cancel") {
      ElMessage.error("请求失败，请稍后再试");
    }
  }
}
</script>

<template>
  <div class="content">
    <div class="page-header">
      <h1>我的收藏</h1>
      <p>查看您已收藏的图书列表，可随时取消收藏</p>
    </div>
    <div class="bookList">
      <div
        class="book"
        v-for="(collection, index) in favoriteList"
        :key="index"
      >
        <div class="img" @click="router.push(`/details/${collection.book.id}`)">
          <img :src="`/img/${collection.book.img}`" />
        </div>
        <div class="info">
          <div
            class="title"
            @click="router.push(`/details/${collection.book.id}`)"
          >
            {{ collection.book.title }}
          </div>
          <div class="actions">
            <button class="unfavorite" @click="cancelCollection(collection.id)">
              取消收藏
            </button>
          </div>
        </div>
      </div>
    </div>
    <div v-if="favoriteList.length === 0" class="empty-state">
      <img src="/img/empty.svg" />
      <p class="empty-text">暂无收藏的书籍</p>
      <span class="empty-tip">快去添加你喜欢的图书吧！</span>
    </div>
  </div>
</template>

<style scoped>
@import "../assets/css/collection.css";
</style>
